<template>
  <div v-if="profileLoading" class="flex justify-center py-8">
    <LoadingSpinner />
  </div>
  
  <div v-else-if="!userId" class="text-center py-8 text-text-secondary">
    请先登录以查看个人资料
  </div>
  
  <form v-else class="flex flex-col gap-6" @submit.prevent="handleSubmit">
    <div class="flex items-center gap-4">
      <div class="w-16 h-16 rounded-full bg-gradient-ai flex items-center justify-center text-2xl text-white font-bold overflow-hidden">
        <img v-if="avatarUrl" :src="avatarUrl" alt="头像" class="w-full h-full object-cover" />
        <span v-else>{{ displayName[0]?.toUpperCase() || 'U' }}</span>
      </div>
      <input type="file" class="hidden" ref="fileInput" @change="onFileChange" accept="image/*" />
      <UiButton type="button" variant="secondary" @click="triggerFile">更换头像</UiButton>
    </div>
    
    <div>
      <label class="block text-text-secondary mb-2">昵称</label>
      <input v-model="displayName" class="input w-full" placeholder="请输入昵称" />
    </div>
    
    <div>
      <label class="block text-text-secondary mb-2">简介</label>
      <textarea v-model="bio" class="input w-full" rows="3" placeholder="请输入个人简介" />
    </div>
    
    <div v-if="error" class="text-red-500 text-sm">{{ error }}</div>
    <div v-if="successMessage" class="text-green-500 text-sm">{{ successMessage }}</div>
    
    <UiButton type="submit" variant="primary" :disabled="saving">
      {{ saving ? '保存中...' : '保存' }}
    </UiButton>
  </form>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { UiButton } from '../ui'
import { LoadingSpinner } from '../ui'
import { useUserStore } from '../../store/useUserStore'
import type { User } from '../../types/ui'
import { supabase } from '../../lib/supabase'

const userStore = useUserStore()
const { user, userId, userProfile, profileLoading } = storeToRefs(userStore)

const avatarUrl = ref<string>('')
const displayName = ref('')
const bio = ref('')
const saving = ref(false)
const successMessage = ref('')
const error = ref('')
const fileInput = ref<HTMLInputElement | null>(null)

// 获取用户资料
const loadUserProfile = async () => {
  if (!userId.value) {
    console.log('No user ID available')
    return
  }
  
  console.log('Loading profile for user:', userId.value)
  
  // 如果 store 中已有用户资料，直接使用
  if (userProfile.value) {
    const profile = userProfile.value as User
    displayName.value = profile.name || ''
    bio.value = profile.bio || ''
    avatarUrl.value = profile.avatar || ''
  } else {
    // 否则从 store 获取用户资料
    await userStore.fetchUserProfile(userId.value)
    if (userProfile.value) {
      const profile = userProfile.value as User
      displayName.value = profile.name || ''
      bio.value = profile.bio || ''
      avatarUrl.value = profile.avatar || ''
    } else {
      // 如果没有找到用户资料，设置默认值
      displayName.value = user.value?.email?.split('@')[0] || '用户'
      bio.value = '热爱虚构电影与AI创作。'
      avatarUrl.value = ''
    }
  }
}

// 触发文件选择
const triggerFile = () => fileInput.value?.click()

// 处理文件选择并上传到 Supabase Storage
const onFileChange = async (e: Event) => {
  const files = (e.target as HTMLInputElement).files
  if (!files || !files[0] || !userId.value) return

  const file = files[0]
  const fileExt = file.name.split('.').pop()
  const fileName = `${userId.value}-${Date.now()}.${fileExt}`
  const filePath = `avatars/${fileName}`

  try {
    // 基础校验：头像类型与大小
    const MAX_IMAGE_BYTES = 5 * 1024 * 1024
    const ALLOWED_IMAGE_MIME_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])
    if (!ALLOWED_IMAGE_MIME_TYPES.has(file.type)) {
      throw new Error('仅支持 JPG/PNG/WebP 图片作为头像')
    }
    if (file.size > MAX_IMAGE_BYTES) {
      throw new Error('头像大小不能超过 5MB')
    }

    const { error: uploadError } = await supabase.storage
      .from('avatars')
      .upload(filePath, file, { cacheControl: '3600', upsert: true, contentType: file.type })

    if (uploadError) {
      throw uploadError
    }

    const { data: urlData } = supabase.storage.from('avatars').getPublicUrl(filePath)
    avatarUrl.value = urlData.publicUrl
  } catch (err) {
    console.error('头像上传失败:', err)
    error.value = err instanceof Error ? err.message : '头像上传失败，请重试'
  }
}

// 处理表单提交
const handleSubmit = async () => {
  if (!userId.value) return
  
  saving.value = true
  successMessage.value = ''
  error.value = ''
  
  try {
    const updates: Partial<User> = {
      name: displayName.value,
      bio: bio.value,
      avatar: avatarUrl.value
    }
    
    console.log('Updating profile with:', updates)
    const result = await userStore.updateUserProfile(updates)
    
    if (result) {
      successMessage.value = '用户资料更新成功！'
      console.log('Profile updated successfully')
    } else {
      error.value = '更新失败，请重试'
    }
  } catch (err) {
    console.error('更新用户资料失败:', err)
    error.value = '更新失败，请重试'
  } finally {
    saving.value = false
  }
}

// 组件挂载时加载用户资料
onMounted(() => {
  loadUserProfile()
})
</script>